"use client";

import { createContext, useContext, useEffect, useMemo, useState } from "react";

interface AuthContextValue {
  authenticated: boolean;
  roles: string[];
  login: (token: string) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextValue | undefined>(undefined);
const STORAGE_KEY = "agent-society-token";

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [token, setToken] = useState<string | null>(null);
  const [roles, setRoles] = useState<string[]>([]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const stored = window.localStorage.getItem(STORAGE_KEY);
    if (stored) {
      setToken(stored);
      setRoles(["operator"]);
    }
  }, []);

  const value = useMemo<AuthContextValue>(
    () => ({
      authenticated: Boolean(token),
      roles,
      login: async (incoming: string) => {
        window.localStorage.setItem(STORAGE_KEY, incoming);
        setToken(incoming);
        setRoles(["operator", "governance"]);
      },
      logout: () => {
        window.localStorage.removeItem(STORAGE_KEY);
        setToken(null);
        setRoles([]);
      }
    }),
    [token, roles]
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) {
    throw new Error("useAuth must be used within AuthProvider");
  }
  return ctx;
}
